package com.clothing.customization.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传配置类
 */
@Configuration
@Slf4j
public class FileUploadConfig implements WebMvcConfigurer {
    
    @Value("${file.upload.path:uploads}")
    private String uploadPath;
    
    @Value("${file.upload.access-path:/uploads/**}")
    private String accessPath;
    
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保上传目录存在，使用绝对路径
        String absolutePath;
        
        // 如果配置的是相对路径，转换为绝对路径
        if (uploadPath.startsWith("./") || !uploadPath.startsWith("/")) {
            // 获取当前工作目录
            String userDir = System.getProperty("user.dir");
            Path path = Paths.get(userDir, uploadPath.replace("./", ""));
            absolutePath = path.toAbsolutePath().toString();
        } else {
            absolutePath = uploadPath;
        }
        
        // 确保目录存在
        try {
            Path dirPath = Paths.get(absolutePath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
                log.info("创建上传目录: {}", absolutePath);
            }
        } catch (IOException e) {
            log.error("创建上传目录失败: {}", absolutePath, e);
            throw new RuntimeException("无法创建文件上传目录: " + e.getMessage(), e);
        }
        
        log.info("文件上传目录: {}", absolutePath);
        log.info("文件访问路径: {}", accessPath);
        
        // 配置静态资源访问路径，确保路径后面有分隔符
        String resourceLocation = "file:" + absolutePath;
        if (!resourceLocation.endsWith(File.separator)) {
            resourceLocation += File.separator;
        }
        
        registry.addResourceHandler(accessPath)
                .addResourceLocations(resourceLocation);
                
        // 添加Swagger UI资源映射
        registry.addResourceHandler("/swagger-ui*/**")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
} 